<template>
  <view class="container">
    <view class="header">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="title">欢迎登录</text>
    </view>
    
    <view class="form-container">
      <view class="input-wrapper">
        <input 
          class="input" 
          v-model="loginForm.phone" 
          type="number" 
          :maxlength="11"
          placeholder="请输入手机号" 
          placeholder-style="color: #999;"
        />
      </view>
      
      <view class="input-wrapper">
        <input 
          class="input" 
          v-model="loginForm.password" 
          type="safe-password" 
          placeholder="请输入密码" 
          placeholder-style="color: #999;"
        />
      </view>
      
      <button class="login-button" @tap="handleLogin">登录</button>
      
      <view class="extra-options">
        <text @tap="showRegisterCard" class="link">立即注册</text>
      </view>
    </view>
    
    <view class="footer">
      <checkbox-group @change="onAgreementChange">
        <label class="agreement">
          <checkbox value="agree" :checked="agreed" />
          <text class="agreement-text">
            我已阅读并同意
            <text class="agreement-link">《用户协议》</text>
            和
            <text class="agreement-link">《隐私政策》</text>
          </text>
        </label>
      </checkbox-group>
    </view>
    
    <!-- 注册卡片弹窗 -->
    <view v-if="showRegister" class="popup-overlay" @tap="closeRegisterCard">
      <view class="register-card" @tap.stop>
        <view class="card-header">
          <text class="card-title">用户注册</text>
        </view>
        
        <view class="card-body">
          <view class="input-wrapper">
            <input 
              class="input" 
              v-model="registerForm.phone" 
              type="number" 
              :maxlength="11"
              placeholder="请输入手机号" 
              placeholder-style="color: #999;"
            />
          </view>
          
          <view class="input-row">
            <view class="input-wrapper code-input">
              <input 
                class="input" 
                v-model="registerForm.code" 
                type="number" 
                :maxlength="6"
                placeholder="请输入验证码" 
                placeholder-style="color: #999;"
              />
            </view>
            <button 
              class="code-button" 
              @tap="getRegisterCode"
              :disabled="registerCodeTimer > 0"
            >
              {{ registerCodeButtonText }}
            </button>
          </view>
          
          <view class="input-wrapper">
            <input 
              class="input" 
              v-model="registerForm.password" 
              type="safe-password" 
              placeholder="请输入密码(6-20位)" 
              placeholder-style="color: #999;"
            />
          </view>
          
          <view class="input-wrapper">
            <input 
              class="input" 
              v-model="registerForm.confirmPassword" 
              type="safe-password" 
              placeholder="请再次输入密码" 
              placeholder-style="color: #999;"
            />
          </view>
        </view>
        
        <view class="card-footer">
          <button class="cancel-button" @tap="closeRegisterCard">取消</button>
          <button class="confirm-button" @tap="handleRegister">注册</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { validatePhone, validatePassword, validateCode } from '@/utils/validate';
import { login, register, sendSmsCode, getCustomerIdByPhone, getUserProfile } from '@/api/auth';

const userStore = useUserStore();

// 定义登录表单数据
const loginForm = ref({
  phone: '',
  password: ''
});

// 定义注册表单数据
const registerForm = ref({
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
});

// 用户协议勾选状态
const agreed = ref(false);

// 控制注册卡片显示
const showRegister = ref(false);

// 注册验证码按钮文字和倒计时
const registerCodeButtonText = ref('获取验证码');
const registerCodeTimer = ref(0);
let registerTimer: number | null = null;

// 处理用户协议勾选变化
const onAgreementChange = (e: any) => {
  agreed.value = e.detail.value.length > 0;
};

// 显示注册卡片
const showRegisterCard = () => {
  showRegister.value = true;
};

// 关闭注册卡片
const closeRegisterCard = () => {
  showRegister.value = false;
  // 清空注册表单
  registerForm.value = {
    phone: '',
    code: '',
    password: '',
    confirmPassword: ''
  };
  
  // 清除注册定时器
  if (registerTimer) {
    clearInterval(registerTimer);
    registerTimer = null;
  }
  registerCodeTimer.value = 0;
  registerCodeButtonText.value = '获取验证码';
};

// 获取注册验证码
const getRegisterCode = async () => {
  if (registerCodeTimer.value > 0) return;
  
  // 验证手机号
  if (!validatePhone(registerForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 调用发送验证码接口
    const result = await sendSmsCode(registerForm.value.phone);
    console.log('验证码发送结果:', result);

    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    });
    
    // 开始倒计时
    registerCodeTimer.value = 60;
    registerCodeButtonText.value = `${registerCodeTimer.value}秒后重试`;
    
    registerTimer = setInterval(() => {
      registerCodeTimer.value--;
      if (registerCodeTimer.value > 0) {
        registerCodeButtonText.value = `${registerCodeTimer.value}秒后重试`;
      } else {
        registerCodeButtonText.value = '获取验证码';
        if (registerTimer) {
          clearInterval(registerTimer);
          registerTimer = null;
        }
      }
    }, 1000) as unknown as number;
    
  } catch (error: any) {
    console.error('获取验证码失败:', error);
  }
};

// 处理注册
const handleRegister = async () => {
  // 表单验证
  if (!validatePhone(registerForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  if (!validateCode(registerForm.value.code)) {
    uni.showToast({
      title: '请输入6位验证码',
      icon: 'none'
    });
    return;
  }
  
  if (!validatePassword(registerForm.value.password)) {
    uni.showToast({
      title: '密码长度为6-20位',
      icon: 'none'
    });
    return;
  }
  
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    uni.showToast({
      title: '两次输入密码不一致',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 调用注册接口
    const result = await register({
      phoneNumber: registerForm.value.phone,
      password: registerForm.value.password,
      confirmPassword: registerForm.value.confirmPassword,
      code: registerForm.value.code
    });

    console.log('注册结果:', result);
    
    uni.showToast({
      title: '注册成功',
      icon: 'success'
    });
    
    // 关闭注册卡片并自动填充登录信息
    setTimeout(() => {
      loginForm.value.phone = registerForm.value.phone;
      loginForm.value.password = registerForm.value.password;
      closeRegisterCard();
    }, 1500);
    
  } catch (error: any) {
    console.error('注册失败:', error);
    // 错误已经在 request 拦截器中处理
  }
};

// 处理登录
const handleLogin = async () => {
  // 表单验证
  if (!validatePhone(loginForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }

  if (!validatePassword(loginForm.value.password)) {
    uni.showToast({
      title: '密码长度为6-20位',
      icon: 'none'
    });
    return;
  }

  if (!agreed.value) {
    uni.showToast({
      title: '请先阅读并同意用户协议',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({title: '登录中...'});

    // 调用登录接口
    const loginData = await login({
      phoneNumber: loginForm.value.phone,
      passwordHash: loginForm.value.password
    });

    console.log('登录接口返回:', loginData);

    const token = loginData.token;

    // 检查返回数据
    if (!token) {
      throw new Error('登录失败,未获取到token');
    }

    // ⭐ 先保存 token,这样后续请求才能携带 token
    uni.setStorageSync('token', token);
    userStore.setToken(token);
    console.log('Token 已保存');

    const customerId = await getCustomerIdByPhone(loginForm.value.phone);
    console.log('用户ID:', customerId);

    if (!customerId) {
      throw new Error('获取用户ID失败');
    }

    const userInfo = await getUserProfile(customerId);
    console.log('用户信息:', userInfo);

    //保存到 Pinia Store
    await userStore.login(token, {
      customerId: customerId,
      phone: userInfo.phoneNumber || loginForm.value.phone,
      nickname: userInfo.nickname || '用户',
      avatar: userInfo.avatarUrl || '/static/logo.png',
      address: userInfo.address || '',
      regionId: userInfo.regionId || 1
    });

    uni.hideLoading();

    uni.showToast({
      title: '登录成功',
      icon: 'success'
    });

    setTimeout(() => {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }, 1000);
    
  } catch (error: any) {
    uni.hideLoading();
    console.error('登录失败:', error);
    
    // 登录失败时清除可能已保存的 token
    uni.removeStorageSync('token');
    userStore.setToken('');
    
    // 只有当错误消息不是来自 request 拦截器时才显示
    if (error.message && !error.message.includes('请求失败')) {
      uni.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      });
    }
  }
};
</script>

<style>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 0 40rpx;
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 160rpx;
  margin-bottom: 80rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 30rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  flex: 1;
}

.input-wrapper {
  background-color: #f8f8f8;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
  padding: 20rpx;
}

.input {
  height: 60rpx;
  font-size: 30rpx;
  color: #333;
}

.login-button {
  height: 80rpx;
  line-height: 80rpx;
  background-color: #00C853;
  color: #fff;
  border-radius: 10rpx;
  font-size: 32rpx;
  margin-top: 50rpx;
}

.extra-options {
  display: flex;
  justify-content: center;
  margin-top: 30rpx;
  font-size: 26rpx;
  color: #666;
}

.link {
  color: #00C853;
}

.footer {
  padding: 40rpx 0 60rpx;
  text-align: center;
}

.agreement {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #999;
}

.agreement-text {
  margin-left: 10rpx;
}

.agreement-link {
  color: #00C853;
  margin: 0 5rpx;
}

/* 弹窗遮罩层 */
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

/* 注册卡片 */
.register-card {
  width: 80%;
  max-width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.card-header {
  padding: 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.card-body {
  padding: 30rpx;
}

.input-row {
  display: flex;
  margin-bottom: 30rpx;
}

.code-input {
  flex: 1;
  margin-right: 20rpx;
  margin-bottom: 0;
}

.code-button {
  width: 180rpx;
  height: 100rpx;
  line-height: 100rpx;
  background-color: #00C853;
  color: #fff;
  border-radius: 10rpx;
  font-size: 24rpx;
  padding: 0;
}

.code-button[disabled] {
  background-color: #ccc;
}

.card-footer {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.cancel-button,
.confirm-button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 10rpx;
  font-size: 32rpx;
}

.cancel-button {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-button {
  background-color: #00C853;
  color: #fff;
}
</style>